<template>
  <div>
    <el-tabs v-model="activeTabDetail" @tab-click="handleTabClick">
      <el-tab-pane label="基本信息" name="info">
        <el-descriptions :border="true" style="margin-bottom: -1px">
          <el-descriptions-item label="展示图片">
            <FileUpload
              :iconList="['preview']"
              type="img"
              v-model:fileList="detailData.Pictrues"
            >
            </FileUpload>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions :border="true" style="margin-bottom: -1px">
          <el-descriptions-item label="编号">{{
            detailData.Code
          }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{
            detailData.Name
          }}</el-descriptions-item>
          <el-descriptions-item label="管理员">{{
            $filterUserName(detailData.Principal)
          }}</el-descriptions-item>
          <el-descriptions-item label="区域">{{
            detailData.Area
          }}</el-descriptions-item>
          <el-descriptions-item label="场地">{{
            detailData.Place
          }}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{
            detailData.Model
          }}</el-descriptions-item>
          <el-descriptions-item label="生产厂商">{{
            detailData.Manufacturer
          }}</el-descriptions-item>
          <el-descriptions-item label="入厂时间">{{
            $slice(detailData.FactoryTime, 0, 10)
          }}</el-descriptions-item>
          <el-descriptions-item label="类别">{{
            detailData.Type
          }}</el-descriptions-item>
          <el-descriptions-item label="是否启用"
            >{{ detailData.Enable == 'Y' ? '启用' : '停用' }}
          </el-descriptions-item>
          <el-descriptions-item label="状况" v-if="props.Category == 2">
            <el-tag effect="dark" :type="State_SelfType[detailData.State_Self]"
              >{{ State_Self[detailData.State_Self] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            :label="props.Category == 2 ? '过程状况' : '状况'"
          >
            <el-tag effect="dark" :type="StateType[detailData.State]">{{
              State[detailData.State]
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址" v-if="props.Category == 1"
            >{{ detailData.IPAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="创建人"
            >{{ $filterUserName(detailData.CreateUser) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间"
            >{{ detailData.CreateTime }}
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions :border="true" :column="1">
          <el-descriptions-item label="应用范围">{{
            detailData.UseScope
          }}</el-descriptions-item>
          <el-descriptions-item label="附件">
            <FileUpload
              v-model:fileList="detailData.Files"
              :detail="true"
              :showBtn="false"
              :showSort="true"
            />
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane :label="props.PlanName + '记录'" name="record">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="searchStatus"
        >
          <el-form-item label="编号">
            <el-input
              v-model="queryParams.Number"
              placeholder="请输入"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item
            :label="props.PlanName + '结果'"
            v-if="props.Category == 1"
          >
            <el-select
              v-model="queryParams.Finish_Result"
              placeholder="请选择"
              clearable
            >
              <el-option label="合格" :value="1"></el-option>
              <el-option label="不合格" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="props.PlanName + '结果'"
            v-if="props.Category == 2"
          >
            <el-select
              v-model="queryParams.Finish_ResultTools"
              placeholder="请选择"
              clearable
            >
              <el-option label="正常" :value="1"></el-option>
              <el-option label="降级" :value="2"></el-option>
              <el-option label="报废" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="props.PlanName + '状态'">
            <el-select
              v-model="queryParams.IsFinish"
              placeholder="请选择"
              clearable
            >
              <el-option
                :label="props.PlanName + '完成'"
                value="true"
              ></el-option>
              <el-option
                :label="props.PlanName + '中'"
                value="false"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <MyTable
          :tableList="recordList"
          :total="Total"
          :columns="columns"
          v-model:page="page"
          v-model:searchStatus="searchStatus"
          :btnList="[]"
          :customBtn="[
            {
              name: '保养',
              rule: { key: 'FinishTime', status: null },
              color: '#67C23A'
            }
          ]"
          @link="handleDetail"
          @getList="getList"
          @delete="handleDelete"
          @custom="handleMaintain"
        >
          <template v-slot:tabTop>
            <el-button
              type="primary"
              icon="CirclePlusFilled"
              @click="handleAddMaintain"
              >添加{{ props.PlanName }}</el-button
            >
          </template>
        </MyTable>
      </el-tab-pane>
      <el-tab-pane label="记录日志" name="three">
        <MyTable
          :tableList="tableLogList"
          :columns="recordLogCol"
          :toolbar="false"
          :btnList="[]"
          :total="total2"
          v-model:page="page2"
        ></MyTable>
      </el-tab-pane>
    </el-tabs>
    <!-- 选择保养方案 -->
    <MyDialog
      v-model:show="showMaintain"
      :title="'选择' + props.PlanName + '方案'"
      :formRef="formRef"
      @confirm="chooseMaintainPlan"
    >
      <MyTable
        :tableList="maintainPlan"
        :columns="maintainPlanColumns"
        :toolbar="false"
        :btnList="[]"
        @radio="handleRadio"
      ></MyTable>
    </MyDialog>
    <!-- 提交保养 -->
    <MyDialog
      v-model:show="showSubmitMaintain"
      :title="props.Label + props.PlanName"
      :formRef="formRef"
      @confirm="submitMaintain"
    >
      <el-form
        :model="formData"
        ref="formRef"
        :inline="true"
        :rules="maintainRules"
        class="wid100"
        label-width="100px"
      >
        <el-row>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="配件费用" prop="Fittings">
              <el-input
                v-model="formData.Fittings"
                placeholder="请输入"
                clearable
                v-number
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="配件说明" prop="Fittings_Remark">
              <el-input
                v-model="formData.Fittings_Remark"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="工时损失费" prop="WorkHours">
              <el-input
                v-model="formData.WorkHours"
                placeholder="请输入"
                clearable
                v-number
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="工时损失说明" prop="WorkHours_Remark">
              <el-input
                v-model="formData.WorkHours_Remark"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="委外费用" prop="Outsource">
              <el-input
                v-model="formData.Outsource"
                placeholder="请输入"
                clearable
                v-number
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="委外说明" prop="Outsource_Remark">
              <el-input
                v-model="formData.Outsource_Remark"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="其他费用" prop="Other">
              <el-input
                v-model="formData.Other"
                placeholder="请输入"
                clearable
                v-number
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="其他说明" prop="Other_Remark">
              <el-input
                v-model="formData.Other_Remark"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </MyCol>
          <MyCol v-if="maintainType == 1">
            <el-form-item label="总费用" prop="Fittings">
              {{ totalFee }}元
            </el-form-item>
          </MyCol>
          <MyCol>
            <el-form-item
              :label="props.PlanName + '结果'"
              v-if="props.Category == 1"
              prop="Finish_Result"
            >
              <el-select v-model="formData.Finish_Result" placeholder="请选择">
                <el-option label="合格" :value="1"></el-option>
                <el-option label="不合格" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :label="props.PlanName + '结果'"
              v-if="props.Category == 2"
              prop="Finish_ResultTools"
            >
              <el-select
                v-model="formData.Finish_ResultTools"
                placeholder="请选择"
              >
                <el-option label="正常" :value="1"></el-option>
                <el-option label="降级" :value="2"></el-option>
                <el-option label="报废" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </MyCol>
        </el-row>
        <el-row>
          <el-form-item label="备注说明" prop="Remark">
            <el-input
              v-model="formData.Remark"
              placeholder="请输入"
              clearable
              type="textarea"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="附件">
            <FileUpload :detail="false" v-model:fileList="maintainFile" />
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        :data="maintainItemList"
        v-if="maintainItemList.length"
        row-class-name="TableRowClass"
        header-row-class-name="TableHeaderClass"
      >
        <el-table-column
          type="index"
          :align="'center'"
          label="序号"
          width="80px"
        >
        </el-table-column>
        <el-table-column
          prop="Code"
          :align="'center'"
          label="编号"
          width="160px"
        >
        </el-table-column>
        <el-table-column prop="Content" :align="'center'" label="保养项内容">
        </el-table-column>
        <el-table-column
          prop="State"
          label="是否合格"
          width="80"
          :align="'center'"
        >
          <template v-slot="{ row }">
            <el-switch
              v-model="row.State"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              :active-value="1"
              :inactive-value="2"
            />
          </template>
        </el-table-column>
      </el-table>
    </MyDialog>
    <!-- 保养详情 -->
    <MyDialog
      v-model:show="showMaintainDetail"
      :title="props.PlanName + '详情'"
      width="800px"
      :showFooter="false"
    >
      <MaintainDetail :PlanName="props.PlanName" :detailData="maintainDetail" />
    </MyDialog>
  </div>
</template>

<script setup name="DeviceDetail">
import { computed } from 'vue';
import MaintainDetail from '@/views/teachingDevice/DeviceAccount/MaintainDetail';
import { GetMaintainDataList_Page } from '@/api/teachDevice/maintain.js';
import { GetDeviceLog_Page } from '@/api/teachDevice/account.js';
import {
  DeviceStartMaintain,
  DeviceEndMaintain
} from '@/api/teachDevice/maintain.js';
import {
  GetMaintainPlanDetail,
  GetMaintainDataDetail
} from '@/api/teachDevice/maintain.js';
const emit = defineEmits(['getList', 'update:showDetail']);
const { proxy } = getCurrentInstance();
const props = defineProps({
  PlanName: {},
  detailData: {},
  Category: {},
  Label: {},
  showDetail: {}
});
const State_Self = {
  1: '正常',
  2: '降级',
  3: '报废'
};
const State_SelfType = {
  1: 'success',
  2: 'danger',
  3: 'info'
};
const State = {
  1: props.Category == 1 ? '正常运行' : '在库',
  2: props.Category == 1 ? '保养中' : '检验中',
  3: '维修中',
  4: '使用中'
};
const StateType = {
  1: 'success',
  2: 'warning',
  3: 'danger',
  4: ''
};
const IsFinish = {
  1: '保养完成',
  2: '保养中'
};
const maintainItemList = ref([]);
const maintainFile = ref([]);
const formData = ref({
  Fittings: '', //配件费用
  Fittings_Remark: '', //配件说明
  WorkHours: '', //工时损失费用
  WorkHours_Remark: '', //工时损失说明
  Outsource: '', //委外费用
  Outsource_Remark: '', //委外说明
  Other: '', //其他费用
  Other_Remark: '', //其他说明
  Total: '', //总费用 (把上面几项费用相加)
  Remark: '', //备注说明
  Finish_Result: '', //保养结果 - 1:合格 2:不合格
  Finish_ResultTools: '' //工具保养结果 - 1:正常 2:降级 3:报废
});
const maintainPlan = computed(() => props.detailData.Maintain);
const detailData = computed(() => props.detailData.Info);
const activeTabDetail = ref('info');
const maintainType = ref();
const startMaintainData = ref({
  ID_MaintainPlan: ''
});
const showSubmitMaintain = ref(false);
const planRules = ref({
  ID_MaintainPlan: [{ required: true, message: '请选择', trigger: 'change' }]
});
const maintainRules = ref({
  Finish_Result: [{ required: true, message: '请选择', trigger: 'change' }],
  Finish_ResultTools: [{ required: true, message: '请选择', trigger: 'change' }]
});
const page = ref({
  PageIndex: 1,
  PageSize: 10
});
const page2 = ref({
  PageIndex: 1,
  PageSize: 10
});
const total2 = ref(0);
const formRef = ref({});
const queryParams = ref({
  Number: '',
  Name: '',
  Finish_Result: '',
  Finish_ResultTools: '',
  IsFinish: '',
  NoPage: ''
});

const Total = ref(0);
const searchStatus = ref(false);
const recordList = ref([]);
const showMaintain = ref(false);
const maintainDetail = ref({});
const showMaintainDetail = ref(false);
const maintainPlanColumns = ref([
  { label: '单选框', width: 80, prop: 'ID' },
  { label: '序号' },
  { label: '编号', prop: 'Code_MaintainPlan' },
  { label: '方案名称', prop: 'Name_MaintainPlan' },
  { label: '工具物资间隔(分钟)', prop: 'Interval' },
  { label: '最后一次保养时间', prop: 'LastMaintainTime' },
  { label: '负责人', prop: 'Principal', user: true },
  { label: '备注', prop: 'Remark' }
]);
const tableLogList = ref([]);
const recordLogCol = ref([
  { label: '序号' },
  { label: '编号', prop: 'Number' },
  { label: '日志信息', prop: 'Message' },
  { label: '创建时间', prop: 'CreateTime' },
  { label: '创建人', prop: 'CreateUser', user: true }
]);
proxy.$formatKey(recordLogCol.value);
proxy.$formatKey(maintainPlanColumns.value);
const columns = ref([
  { label: '序号' },
  { label: '编号', prop: 'Number', link: true, self: true },
  { label: '保养方案', prop: 'Name_Maintain' },
  { label: '总费用', prop: 'Total' },
  { label: '备注说明', prop: 'Remark' },
  {
    label: `${props.PlanName}状态`,
    tag: true,
    prop: 'IsFinishName'
  },
  {
    label: `${props.PlanName}结果`,
    tag: true,
    prop: 'Finish_ResultName'
  },

  { label: '操作', width: 160 }
]);
if (props.Category == 1) {
  columns.value = columns.value?.filter(item => item.label != '状况');
}
proxy.$formatKey(columns.value);

async function getList() {
  try {
    let query = {
      ...page.value,
      Device: detailData.value.ID,
      ...queryParams.value
    };
    let res = await GetMaintainDataList_Page(query);
    res.data.List?.forEach(item => {
      item.IsFinishName = [
        {
          type: item.FinishTime ? 'success' : 'warning',
          name: item.FinishTime
            ? `${props.PlanName}完成`
            : `${props.PlanName}中`
        }
      ];
      if (item.Finish_Result || item.Finish_ResultTools) {
        item.Finish_ResultName = [
          {
            type:
              item.Finish_Result == 1 || item.Finish_ResultTools == 1
                ? 'success'
                : 'danger',
            name:
              item.Finish_Result == 1 || item.Finish_ResultTools == 1
                ? '合格'
                : '不合格'
          }
        ];
      }
    });
    recordList.value = res.data.List;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}

async function submitMaintain(val) {
  if (val) {
    try {
      let query = {
        ...formData.value,
        Total: totalFee.value,
        Files: maintainFile.value?.map(item => {
          return {
            FileID: item.ID,
            Sort: item.Sort
          };
        }),
        Items: maintainItemList.value?.map(item => {
          return {
            Code: item.Code, //保养项编号
            Content: item.Content, //保养项内容
            State: item.State //保养项状态 1:合格 2:不合格
          };
        })
      };
      await DeviceEndMaintain(query);
      proxy.$modal.msgSuccess('提交成功');
      showSubmitMaintain.value = false;
      getList();
      emit('update:showDetail', false);
      emit('getList');
    } catch (error) {
      console.log(error);
    }
  }
}

async function handleMaintain(row) {
  try {
    reset();
    formData.value.ID = row.ID;
    if (row.ID_MaintainPlan == 0) {
      maintainType.value = 2;
    } else {
      maintainType.value = 1;
      let query = {
        ID: row.ID_MaintainPlan
      };
      let res = await GetMaintainPlanDetail(query);
      res.data.Items?.forEach(item => {
        item.State = 1;
      });
      maintainItemList.value = res.data.Items;
    }
    showSubmitMaintain.value = true;
  } catch (error) {
    console.log(error);
  }
}

const totalFee = computed({
  get: () => {
    return (
      Number(formData.value.Fittings) +
      Number(formData.value.WorkHours) +
      Number(formData.value.Outsource) +
      Number(formData.value.Other)
    );
  },
  set: v => {
    console.log(v);
  }
});

function handleRadio(row) {
  startMaintainData.value.ID_MaintainPlan = row.ID_MaintainPlan;
  startMaintainData.value.Name_Maintain = row.Name_MaintainPlan;
}

async function chooseMaintainPlan() {
  if (!startMaintainData.value.ID_MaintainPlan) {
    return proxy.$modal.msgError('请先选择方案');
  }
  try {
    let query = {
      ID_Device: detailData.value.ID,
      ...startMaintainData.value
    };
    let res = await DeviceStartMaintain(query);
    let row = {
      ID: res.data,
      ID_MaintainPlan: startMaintainData.value.ID_MaintainPlan
    };
    handleMaintain(row);
    getList();
    showMaintain.value = false;
  } catch (error) {
    console.log(error);
  }
}

async function handleAddMaintain() {
  if (!maintainPlan.value?.length) {
    return proxy.$modal.msgError('当前' + props.Label + '没有绑定方案');
  }
  let Type = maintainPlan.value[0]['Type'];
  if (Type == 2) {
    maintainPlanColumns.value = maintainPlanColumns.value?.filter(
      item => item.label != '编号' && item.label != '方案名称'
    );
  }
  maintainFile.value = [];
  reset();
  maintainItemList.value = [];
  let bool = recordList.value?.some(item => !item.FinishTime);
  if (!bool) {
    showMaintain.value = true;
  } else {
    proxy.$modal.msgError(
      '当前正在' + props.PlanName + '中，无法添加新的' + props.PlanName
    );
  }
}

async function handleDetail(row) {
  try {
    let res = await GetMaintainDataDetail({ ID: row.ID });
    maintainDetail.value = res.data;
    showMaintainDetail.value = true;
  } catch (error) {
    console.log(error);
  }
}

async function handleDelete(row) {}

function reset() {
  formData.value = {
    Fittings: '', //配件费用
    Fittings_Remark: '', //配件说明
    WorkHours: '', //工时损失费用
    WorkHours_Remark: '', //工时损失说明
    Outsource: '', //委外费用
    Outsource_Remark: '', //委外说明
    Other: '', //其他费用
    Other_Remark: '', //其他说明
    Total: '', //总费用 (把上面几项费用相加)
    Remark: '', //备注说明
    Finish_Result: '', //保养结果 - 1:合格 2:不合格
    Finish_ResultTools: '' //工具保养结果 - 1:正常 2:降级 3:报废
  };
  maintainFile.value = [];
}

function handleTabClick() {
  if (activeTabDetail.value == 'record' && !recordList.value.length) {
    getList();
  }
  if (activeTabDetail.value == 'three') {
    getDeviceLog();
  }
}

async function getDeviceLog() {
  console.log(props.detailData);
  try {
    let query = {
      ID: props.detailData.Info.ID,
      ...page2.value,
      NoPage: ''
    };
    let res = await GetDeviceLog_Page(query);
    tableLogList.value = res.data.List;
    total2.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}

function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Number: '',
    Name: '',
    Finish_Result: '',
    Finish_ResultTools: '',
    IsFinish: '',
    NoPage: ''
  };
  handleQuery();
}
</script>

<style lang="scss" scoped></style>
